<template>
  <div class="contain">
    <div class="header">
      <div class="text">
        <div class="content-wrapper">
          健康档案建档率
          <el-tooltip content="统计近四年辖区内常住居民中已建立健康档案的建档率。同比=[(当期数/上年年同期数)-1]*100%" placement="top" effect="light">
            <img src="@/assets/images/img/yw.png" alt="描述性文字" />
          </el-tooltip>
        </div>
      </div>
      <div class="lable-container">
        <!-- 直接使用 yearlyChangeLabels 中的数据 -->
        <div class="lable" v-for="(item, index) in yearlyChangeLabels" :key="index">
          <span class="circle" :style="{ backgroundColor: colors[index % colors.length] }"></span>
          <div>{{ item.label }}: {{ item.yearlyChange }} &emsp;当前年份同比率：{{ item.latestPercentage }}%</div>
        </div>
      </div>
    </div>
    <div className="container">
      <div ref="chart" style="width: 650px; height: 35vh;"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { nextTick } from 'vue';

export default {
  name: "Healthrecords",
  props: {
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      myChart: null,
      option: null
    };
  },
  computed: {
    colors() {
      return ['#99ACEC', '#FFB6C1', '#fff'];
    },
    // 映射 jkglRateListYearToYear 数据到 yearlyChangeLabels
    yearlyChangeLabels() {
      if (!this.chartData || !this.chartData.jkglRateListYearToYear) return [];
      return this.chartData.jkglRateListYearToYear.map(item => ({
        label: item[0],
        latestPercentage: item[item.length - 1], // 最新百分比，假设是最后一项
        yearlyChange: item[item.length - 2] // 年同比增长率，假设是倒数第二项
      }));
    }
  },
  watch: {
    chartData: {
      handler(newVal) {
        if (newVal && newVal.healthRecordsFilingRateList) {
          this.updateChart();
        } else {
          console.warn('Invalid chartData received:', newVal);
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.initChart();
    if (this.myChart && this.chartData && this.chartData.healthRecordsFilingRateList) {
      this.updateChart();
    } else {
      console.warn('Waiting for chartData to be available before updating the chart.');
    }
  },
  methods: {
    initChart() {
      if (this.$refs.chart) {
        this.myChart = echarts.init(this.$refs.chart);
      } else {
        console.error('Chart container ref is missing.');
      }
    },
    async updateChart() {
      await nextTick();

      if (!this.myChart || !this.chartData || !this.chartData.healthRecordsFilingRateList) {
        console.error('Chart not initialized or no valid data provided.');
        return;
      }

      const healthRecordsFilingRateList = this.chartData.healthRecordsFilingRateList;

      // 构建 series 数据，仅使用建档率的数据
      const seriesData = [{
        name: '建档率',
        type: 'bar',
        barWidth: '25%',
        itemStyle: {
          borderRadius: [5, 5, 0, 0],
          color: this.colors[0] // 使用固定颜色或选择一个合适的颜色
        },
        data: healthRecordsFilingRateList.map(yearData => parseFloat(yearData[1]) || 0), // 只取每年的建档率值
        label: {
          show: true,
          position: 'top',
          formatter: '{c}%' // 格式化标签为百分比形式
        }
      }];

      // 设置 x 轴标签为年份
      const labels = healthRecordsFilingRateList.map(item => item[0]);

      const option = {
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        xAxis: { type: 'category', data: labels },
        yAxis: { type: 'value', axisLabel: { formatter: '{value}%' } }, // y轴也设置为百分比形式
        series: seriesData
      };

      this.myChart.setOption(option);
    }
  },
  beforeDestroy() {
    if (this.myChart) {
      this.myChart.dispose();
      this.myChart = null;
    }
  }
};
</script>

<style scoped>
.contain {
  width: 100%;
  background-color: #fff;
  border-radius: 10px;
  position: relative; /* 确保它是相对定位的容器 */
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
  position: absolute; /* 设置为绝对定位 */
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  /*background-color: #fff; !* 如果需要背景色遮挡下方内容 *!*/
  padding: 20px;
}

.text {
  font-size: 18px;
  font-weight: bold;
  color: #454747;
  display: flex;
  justify-content: flex-start; /* 左对齐 */
  align-items: center; /* 垂直居中 */
  margin-bottom: 10px;
}
.content-wrapper {
  display: flex;
  align-items: center; /* 确保内部元素垂直居中 */
}
.content-wrapper img {
  margin-left: 5px; /* 根据需要调整间距 */
  width: 20px; /* 设置图片宽度，根据实际图片大小调整 */
  height: auto; /* 保持图片比例 */
}
.header img {
  width: 20px;
  height: 20px;
}

.lable-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.lable {
  font-size: 12px;
  color: #454747;
  display: flex;
  align-items: center;
  padding: 2px;
}

.circle {
  width: 10px;
  height: 10px;
  background-color: #f8ac59;
  border-radius: 50%;
  display: inline-block;
  margin-right: 5px;
}

.container {
  position: relative;
  z-index: 1;
  background-color: #fff;
  border-radius: 10px;
  margin-top: 50px;
}
</style>
